

import React, { useState, useEffect } from 'react';
import { Link, useNavigate, useSearchParams } from 'react-router-dom';
import Layout from '../../components/Layout';
import authApi from '../../api/auth';
import studentApi from '../../api/student';

interface Comment {
  id: string;
  userId: string;
  userName: string;
  userAvatar: string;
  rating: number;
  content: string;
  likeCount: number;
  isLiked: boolean;
  date: string;
}

interface CourseDetail {
  id: number;
  name: string;
  period: string;
  price: number;
  registrationTime: string;
  startTime: string;
  endTime: string;
  courseHours: number;
  testTime: string;
  leaderId: number;
  corpId: number;
  subCategoryId: number;
  description: string;
  createTime: string;
  updateTime: string;
}

interface UserProfile {
  id: number;
  gender: string | null;
  avatar: string;
  address: string | null;
  email: string | null;
  userId: number;
  nickName: string;
  age: number | null;
}

interface UserInfo {
  id: number;
  username: string;
  profile: UserProfile;
  roles?: Array<{
    id: number;
    name: string;
    code: string;
  }>;
  currentRole?: {
    id: number;
    name: string;
    code: string;
  };
}

interface ApiResponse {
  code: number;
  message: string;
  data: CourseDetail;
}

const CourseDetailPage: React.FC = () => {
  const navigate = useNavigate();
  const [searchParams] = useSearchParams();
  const [isEnrollModalVisible, setIsEnrollModalVisible] = useState(false);
  const [isWishlisted, setIsWishlisted] = useState(false);
  const [commentText, setCommentText] = useState('');
  const [paymentMethod, setPaymentMethod] = useState('wechat');
  const [courseDetail, setCourseDetail] = useState<CourseDetail | null>(null);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [userInfo, setUserInfo] = useState<UserInfo | null>(null);
  const [userLoading, setUserLoading] = useState(false);
  const [enrolling, setEnrolling] = useState(false);
  const [enrollError, setEnrollError] = useState<string | null>(null);
  const [enrollSuccess, setEnrollSuccess] = useState<string | null>(null);
  const [comments, setComments] = useState<Comment[]>([
    {
      id: '1',
      userId: 'user1',
      userName: '王同学',
      userAvatar: 'https://s.coze.cn/image/vaMCxdK03lk/',
      rating: 5,
      content: '老师讲得很详细，零基础也能跟上。课程内容安排合理，从基础语法到实际项目，循序渐进。练习题也很有针对性，帮助巩固所学知识。强烈推荐给想学习Python的同学！',
      likeCount: 12,
      isLiked: false,
      date: '2024-01-15'
    },
    {
      id: '2',
      userId: 'user2',
      userName: '李同学',
      userAvatar: 'https://s.coze.cn/image/AU6hvSFqB30/',
      rating: 4,
      content: '作为一个完全没有编程基础的人，这个课程真的帮了我很多。老师的讲解很耐心，每个知识点都有详细的例子。现在已经能独立完成一些小项目了，很有成就感！',
      likeCount: 8,
      isLiked: false,
      date: '2024-01-12'
    }
  ]);

  // 设置页面标题
  useEffect(() => {
    const originalTitle = document.title;
    document.title = `${courseDetail?.name || '课程详情'} - 学途`;
    return () => { document.title = originalTitle; };
  }, [courseDetail]);

  // 获取课程ID
  const courseId = searchParams.get('courseId') || 'default';
  const numericCourseId = Number(courseId);

  // 是否已报名当前课程
  const [isEnrolled, setIsEnrolled] = useState<boolean>(false);
  useEffect(() => {
    const checkEnrolled = async () => {
      try {
        setIsEnrolled(false);
        const token = localStorage.getItem('token');
        if (!token || !numericCourseId) return;
        const userResp = await authApi.getUser();
        const userId = userResp?.data?.id;
        if (!userId) return;
        const resp = await studentApi.getEnrolledCourses(userId);
        const list = resp?.data || [];
        const has = list.some((item: any) => Number(item.courseId) === numericCourseId);
        setIsEnrolled(has);
      } catch (err) {
        console.warn('检查课程报名状态失败：', err);
      }
    };
    checkEnrolled();
  }, [numericCourseId]);

  // 获取课程详情
  const fetchCourseDetail = async (id: string) => {
    try {
      setLoading(true);
      setError(null);
      
      // 获取token
      const token = localStorage.getItem('token');
      console.log('正在调用API:', `http://localhost:8086/course/${id}`);
      console.log('Token:', token ? `存在 (${token.substring(0, 20)}...)` : '不存在');
      
      const headers: Record<string, string> = {
        'Content-Type': 'application/json',
      };
      
      // 如果有token，添加Authorization头
      if (token) {
        headers['Authorization'] = `Bearer ${token}`;
      }
      
      const response = await fetch(`http://localhost:8086/course/${id}`, {
        method: 'GET',
        headers,
        credentials: 'include',
      });
      
      console.log('API响应状态:', response.status);
      
      if (!response.ok) {
        if (response.status === 401) {
          throw new Error('需要登录才能访问课程详情');
        } else if (response.status === 404) {
          throw new Error('课程不存在');
        } else {
          throw new Error(`服务器错误 (${response.status})`);
        }
      }
      
      const result: ApiResponse = await response.json();
      console.log('API响应数据:', result);
      
      if (result.code === 0 && result.data) {
        setCourseDetail(result.data);
        console.log('课程详情加载成功:', result.data);
      } else {
        console.error('获取课程详情失败:', result.message);
        setError(result.message || '获取课程详情失败');
      }
    } catch (error) {
      console.error('API调用失败:', error);
      setError(error instanceof Error ? error.message : '网络连接失败，请检查网络或稍后重试');
    } finally {
      setLoading(false);
    }
  };

  // 获取用户信息
  const fetchUserInfo = async () => {
    try {
      setUserLoading(true);
      const token = localStorage.getItem('token');
      if (!token) {
        throw new Error('需要登录才能报名');
      }
      
      const response = await authApi.getUser();
      if (response && response.data) {
        setUserInfo(response.data);
      } else {
        throw new Error('获取用户信息失败');
      }
    } catch (error: any) {
      console.error('获取用户信息失败:', error);
      setEnrollError(error.message || '获取用户信息失败');
    } finally {
      setUserLoading(false);
    }
  };

  // 页面加载时获取课程详情
  useEffect(() => {
    if (courseId && courseId !== 'default') {
      fetchCourseDetail(courseId);
    }
  }, [courseId]);

  // 事件处理函数
  const handleEnrollClick = () => {
    setIsEnrollModalVisible(true);
    setEnrollError(null);
    setEnrollSuccess(null);
    // 获取用户信息
    if (!userInfo) {
      fetchUserInfo();
    }
  };

  const handleWishlistClick = () => {
    setIsWishlisted(!isWishlisted);
    console.log('收藏状态:', !isWishlisted);
  };

  const handleLikeComment = (commentId: string) => {
    setComments(comments.map(comment => 
      comment.id === commentId 
        ? { ...comment, isLiked: !comment.isLiked, likeCount: comment.isLiked ? comment.likeCount - 1 : comment.likeCount + 1 }
        : comment
    ));
  };

  const handleSubmitComment = () => {
    if (commentText.trim()) {
      const newComment: Comment = {
        id: Date.now().toString(),
        userId: 'current-user',
        userName: '当前用户',
        userAvatar: 'https://s.coze.cn/image/default-avatar/',
        rating: 5,
        content: commentText,
        likeCount: 0,
        isLiked: false,
        date: new Date().toLocaleDateString()
      };
      setComments([newComment, ...comments]);
      setCommentText('');
    }
  };

  const handleUserClick = (userId: string) => {
    console.log('查看用户:', userId);
  };

  const handleLoadMoreComments = () => {
    console.log('加载更多评论');
  };

  const handleConfirmEnroll = async () => {
    if (!courseDetail) {
      setEnrollError('课程信息不存在');
      return;
    }

    try {
      setEnrolling(true);
      setEnrollError(null);
      setEnrollSuccess(null);

      const token = localStorage.getItem('token');
      if (!token) {
        throw new Error('需要登录才能报名');
      }

      const response = await fetch(`http://localhost:8086/stu/pick/${courseDetail.id}`, {
        method: 'GET',
        headers: {
          'Content-Type': 'application/json',
          'Authorization': `Bearer ${token}`,
        },
        credentials: 'include',
      });

      const result = await response.json();
      if (response.ok && (result.code === 0 || result.code === 200)) {
        setEnrollSuccess(result.message || result.msg || '选课成功');
        // 报名成功后立即更新页面按钮为“我的课程”
        setIsEnrolled(true);
        // 选课成功后3秒自动关闭弹窗
        setTimeout(() => {
          setIsEnrollModalVisible(false);
        }, 3000);
      } else {
        throw new Error(result.message || result.msg || `报名失败(${response.status})`);
      }
    } catch (error: any) {
      console.error('报名失败:', error);
      setEnrollError(error.message || '报名失败');
    } finally {
      setEnrolling(false);
    }
  };

  const renderStars = (rating: number) => {
    return Array.from({ length: 5 }, (_, index) => (
      <i
        key={index}
        className={`${index < rating ? 'fas' : 'far'} fa-star ${index < rating ? 'text-yellow-500' : 'text-gray-300'} text-sm`}
      />
    ));
  };

  // 处理HTML描述，提取纯文本
  const getPlainTextDescription = (htmlDescription: string) => {
    if (!htmlDescription) return '';
    const tempDiv = document.createElement('div');
    tempDiv.innerHTML = htmlDescription;
    const text = tempDiv.textContent || tempDiv.innerText || '';
    return text;
  };

  // 格式化日期
  const formatDate = (dateString: string) => {
    if (!dateString) return '';
    const date = new Date(dateString);
    return date.toLocaleDateString('zh-CN');
  };

  return (
    <Layout title="课程详情 - 学途">
      <div className="min-h-screen bg-gray-50">
        <div className="max-w-6xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
          {/* 面包屑导航 */}
          <nav className="mb-6">
            <ol className="flex items-center space-x-2 text-sm text-gray-600">
              <li><Link to="/home" className="hover:text-blue-600 transition-colors">首页</Link></li>
              <li><i className="fas fa-chevron-right text-xs"></i></li>
              <li><Link to="/course-list" className="hover:text-blue-600 transition-colors">课程中心</Link></li>
              <li><i className="fas fa-chevron-right text-xs"></i></li>
              <li className="text-gray-900">{courseDetail?.name || '课程详情'}</li>
            </ol>
          </nav>

          {/* 课程信息 */}
          <section className="bg-white rounded-xl shadow-lg mb-8">
            {loading ? (
              <div className="flex justify-center items-center py-12">
                <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-blue-600"></div>
                <span className="ml-3 text-gray-600">加载中...</span>
              </div>
            ) : error ? (
              <div className="p-12 text-center">
                <div className="text-red-500 mb-4">
                  <i className="fas fa-exclamation-triangle text-4xl"></i>
                </div>
                <h3 className="text-lg font-semibold text-gray-900 mb-2">加载失败</h3>
                <p className="text-gray-600 mb-4">{error}</p>
                <div className="flex justify-center space-x-3">
                  {error.includes('登录') ? (
                    <Link 
                      to="/login"
                      className="px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition-colors"
                    >
                      去登录
                    </Link>
                  ) : (
                    <button 
                      onClick={() => fetchCourseDetail(courseId)}
                      className="px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition-colors"
                    >
                      重试
                    </button>
                  )}
                </div>
              </div>
            ) : courseDetail ? (
              <div className="p-8">
                {/* 课程标签 */}
                <div className="flex items-center space-x-2 mb-4">
                  <span className="px-3 py-1 bg-blue-100 text-blue-600 text-sm rounded-full">{courseDetail.period}</span>
                  <span className="px-3 py-1 bg-gray-100 text-gray-600 text-sm rounded-full">{courseDetail.courseHours}课时</span>
                </div>

                {/* 课程标题和基本信息 */}
                <h1 className="text-3xl font-bold text-gray-900 mb-4">{courseDetail.name}</h1>
                
                <div className="flex flex-wrap items-center space-x-6 mb-4 text-sm">
                  <div className="flex items-center space-x-1">
                    <i className="fas fa-clock text-gray-600"></i>
                    <span className="text-gray-600">总时长：{courseDetail.courseHours}小时</span>
                  </div>
                  <div className="flex items-center space-x-1">
                    <i className="fas fa-calendar text-gray-600"></i>
                    <span className="text-gray-600">开课时间：{formatDate(courseDetail.startTime)}</span>
                  </div>
                  <div className="flex items-center space-x-1">
                    <i className="fas fa-calendar-times text-gray-600"></i>
                    <span className="text-gray-600">结束时间：{formatDate(courseDetail.endTime)}</span>
                  </div>
                  {courseDetail.testTime && (
                    <div className="flex items-center space-x-1">
                      <i className="fas fa-clipboard-check text-gray-600"></i>
                      <span className="text-gray-600">考试时间：{formatDate(courseDetail.testTime)}</span>
                    </div>
                  )}
                </div>

                <p className="text-gray-600 mb-6 leading-relaxed">
                  {getPlainTextDescription(courseDetail.description)}
                </p>

                {/* 课程详情 */}
                <div className="mb-6">
                  <h3 className="text-lg font-semibold text-gray-900 mb-4">课程介绍</h3>
                  <div className="space-y-4 text-gray-600 leading-relaxed mb-6">
                    <div dangerouslySetInnerHTML={{ __html: courseDetail.description }} />
                  </div>
                  
                  <h3 className="text-lg font-semibold text-gray-900 mb-4">课程信息</h3>
                  <ul className="space-y-2 text-gray-600 mb-6">
                    <li className="flex items-start space-x-2">
                      <i className="fas fa-calendar text-blue-500 mt-1"></i>
                      <span>开课时间：{formatDate(courseDetail.startTime)}</span>
                    </li>
                    <li className="flex items-start space-x-2">
                      <i className="fas fa-calendar-times text-blue-500 mt-1"></i>
                      <span>结束时间：{formatDate(courseDetail.endTime)}</span>
                    </li>
                    <li className="flex items-start space-x-2">
                      <i className="fas fa-clock text-blue-500 mt-1"></i>
                      <span>课程时长：{courseDetail.courseHours}小时</span>
                    </li>
                    {courseDetail.testTime && (
                      <li className="flex items-start space-x-2">
                        <i className="fas fa-clipboard-check text-blue-500 mt-1"></i>
                        <span>考试时间：{formatDate(courseDetail.testTime)}</span>
                      </li>
                    )}
                  </ul>
                </div>

                {/* 价格和操作按钮 */}
                <div className="flex items-center justify-between bg-gray-50 rounded-lg p-6 mb-6">
                  <div>
                    <span className="text-3xl font-bold text-blue-600">¥{courseDetail.price}</span>
                    <p className="text-gray-600 text-sm">课程价格</p>
                    {isEnrolled && (
                      <p className="mt-2 text-green-600 text-sm">已报名，请前往我的课程查看</p>
                    )}
                  </div>
                  <div className="flex space-x-3">
                    {isEnrolled ? (
                      <Link
                        to="/enrolled-courses"
                        className="px-6 py-3 bg-blue-600 text-white rounded-lg font-medium hover:bg-blue-700 transition-colors"
                      >
                        我的课程
                      </Link>
                    ) : (
                      <button
                        onClick={handleEnrollClick}
                        className="px-6 py-3 bg-blue-600 text-white rounded-lg font-medium hover:bg-blue-700 transition-colors"
                      >
                        立即报名
                      </button>
                    )}
                    <button
                      onClick={handleWishlistClick}
                      className={`px-6 py-3 border border-gray-300 text-gray-600 rounded-lg hover:bg-gray-50 transition-colors ${
                        isWishlisted ? 'bg-red-50' : ''
                      }`}
                    >
                      <i className={`${isWishlisted ? 'fas' : 'far'} fa-heart mr-2`} style={isWishlisted ? { color: '#EF4444' } : {}}></i>
                      加入收藏
                    </button>
                  </div>
                </div>
              </div>
            ) : (
              <div className="p-12 text-center">
                <div className="text-gray-400 mb-4">
                  <i className="fas fa-book-open text-4xl"></i>
                </div>
                <h3 className="text-lg font-semibold text-gray-900 mb-2">课程信息不存在</h3>
                <p className="text-gray-600">请检查课程ID是否正确</p>
              </div>
            )}
          </section>

          {/* 学员评价 */}
          <section className="bg-white rounded-xl shadow-lg">
            <div className="p-8">
              <h2 className="text-2xl font-bold text-gray-900 mb-6">学员评价</h2>
              
              {/* 评分统计 */}
              <div className="flex items-center space-x-8 mb-8">
                <div className="text-center">
                  <span className="text-2xl font-bold text-blue-600">4.8</span>
                  <div className="flex items-center justify-center space-x-1 my-2">
                    {renderStars(5)}
                  </div>
                  <span className="text-gray-600">(126条评价)</span>
                </div>
                <div className="flex items-center space-x-4 text-sm text-gray-600">
                  <span>5星 <span className="text-gray-900 font-medium">85%</span></span>
                  <span>4星 <span className="text-gray-900 font-medium">12%</span></span>
                  <span>3星 <span className="text-gray-900 font-medium">3%</span></span>
                </div>
              </div>

              {/* 发表评论 */}
              <div className="mb-8">
                <h3 className="text-lg font-semibold text-gray-900 mb-4">发表评价</h3>
                <div className="space-y-4">
                  <textarea
                    value={commentText}
                    onChange={(e) => setCommentText(e.target.value)}
                    placeholder="分享你的学习体验..."
                    className="w-full p-4 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-600 focus:border-transparent resize-none"
                    rows={3}
                  />
                  <div className="flex justify-end">
                    <button
                      onClick={handleSubmitComment}
                      className="px-6 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition-colors"
                    >
                      发表评论
                    </button>
                  </div>
                </div>
              </div>

              {/* 评论列表 */}
              <div className="space-y-6">
                {comments.map((comment) => (
                  <div key={comment.id} className="p-4 rounded-lg transition-colors hover:bg-gray-50">
                    <div className="flex items-start space-x-4">
                      <img
                        src={comment.userAvatar}
                        alt={`${comment.userName}头像`}
                        className="w-10 h-10 rounded-full"
                      />
                      <div className="flex-1">
                        <div className="flex items-center space-x-3 mb-2">
                          <span
                            className="font-medium text-gray-900 cursor-pointer"
                            onClick={() => handleUserClick(comment.userId)}
                          >
                            {comment.userName}
                          </span>
                          <div className="flex items-center space-x-1">
                            {renderStars(comment.rating)}
                          </div>
                          <span className="text-gray-600 text-sm">{comment.date}</span>
                        </div>
                        <p className="text-gray-900 mb-3 leading-relaxed">
                          {comment.content}
                        </p>
                        <button
                          onClick={() => handleLikeComment(comment.id)}
                          className="flex items-center space-x-1 text-gray-600 hover:text-red-500 transition-colors"
                        >
                          <i className={`${comment.isLiked ? 'fas' : 'far'} fa-heart`} style={comment.isLiked ? { color: '#EF4444' } : {}}></i>
                          <span>{comment.likeCount}</span>
                        </button>
                      </div>
                    </div>
                  </div>
                ))}
              </div>

              {/* 加载更多 */}
              <div className="text-center mt-8">
                <button
                  onClick={handleLoadMoreComments}
                  className="px-6 py-2 border border-gray-300 text-gray-600 rounded-lg hover:bg-gray-50 transition-colors"
                >
                  查看更多评论
                </button>
              </div>
            </div>
          </section>
        </div>
      </div>

      {/* 报名模态框 */}
      {isEnrollModalVisible && courseDetail && (
        <div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50">
          <div className="bg-white rounded-xl shadow-xl max-w-2xl w-full mx-4 max-h-[90vh] overflow-y-auto">
            <div className="p-6">
              <div className="flex items-center justify-between mb-6">
                <h3 className="text-2xl font-bold text-gray-900">课程报名表</h3>
                <button
                  onClick={() => setIsEnrollModalVisible(false)}
                  className="text-gray-400 hover:text-gray-600 text-2xl"
                >
                  ×
                </button>
              </div>
              
              {/* 加载状态 */}
              {userLoading && (
                <div className="flex items-center justify-center py-8">
                  <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-blue-600"></div>
                  <span className="ml-3 text-gray-600">正在加载用户信息...</span>
                </div>
              )}
              
              {/* 错误提示 */}
              {enrollError && (
                <div className="bg-red-50 border border-red-200 rounded-lg p-4 mb-6">
                  <div className="flex items-center text-red-700">
                    <i className="fas fa-exclamation-triangle mr-2"></i>
                    <span>{enrollError}</span>
                  </div>
                </div>
              )}
              
              {/* 成功提示 */}
              {enrollSuccess && (
                <div className="bg-green-50 border border-green-200 rounded-lg p-4 mb-6">
                  <div className="flex items-center text-green-700">
                    <i className="fas fa-check-circle mr-2"></i>
                    <span>{enrollSuccess}</span>
                  </div>
                </div>
              )}
              
              {/* 用户和课程信息 */}
              {userInfo && !userLoading && (
                <div className="grid grid-cols-1 lg:grid-cols-2 gap-6 mb-6">
                  {/* 用户信息 */}
                  <div className="bg-gray-50 rounded-lg p-4">
                    <h4 className="font-semibold text-gray-900 mb-3">当前用户信息</h4>
                    <div className="space-y-2 text-sm">
                      <div className="flex justify-between">
                        <span className="text-gray-600">学号：</span>
                        <span className="text-gray-900">{userInfo.username}</span>
                      </div>
                      <div className="flex justify-between">
                        <span className="text-gray-600">姓名：</span>
                        <span className="text-gray-900">{userInfo.profile?.nickName || '未设置'}</span>
                      </div>
                      <div className="flex justify-between">
                        <span className="text-gray-600">邮箱：</span>
                        <span className="text-gray-900">{userInfo.profile?.email || '未设置'}</span>
                      </div>
                      <div className="flex justify-between">
                        <span className="text-gray-600">性别：</span>
                        <span className="text-gray-900">{userInfo.profile?.gender || '未设置'}</span>
                      </div>
                      <div className="flex justify-between">
                        <span className="text-gray-600">地址：</span>
                        <span className="text-gray-900">{userInfo.profile?.address || '未设置'}</span>
                      </div>
                    </div>
                  </div>
                  
                  {/* 课程信息 */}
                  <div className="bg-gray-50 rounded-lg p-4">
                    <h4 className="font-semibold text-gray-900 mb-3">课程信息</h4>
                    <div className="space-y-2 text-sm">
                      <div className="flex justify-between">
                        <span className="text-gray-600">课程名称：</span>
                        <span className="text-gray-900">{courseDetail.name}</span>
                      </div>
                      <div className="flex justify-between">
                        <span className="text-gray-600">期数：</span>
                        <span className="text-gray-900">{courseDetail.period}</span>
                      </div>
                      <div className="flex justify-between">
                        <span className="text-gray-600">价格：</span>
                        <span className="text-blue-600 font-semibold">¥{courseDetail.price}</span>
                      </div>
                      <div className="flex justify-between">
                        <span className="text-gray-600">报名时间：</span>
                        <span className="text-gray-900">{formatDate(courseDetail.registrationTime)}</span>
                      </div>
                      <div className="flex justify-between">
                        <span className="text-gray-600">开课时间：</span>
                        <span className="text-gray-900">{formatDate(courseDetail.startTime)}</span>
                      </div>
                      <div className="flex justify-between">
                        <span className="text-gray-600">结束时间：</span>
                        <span className="text-gray-900">{formatDate(courseDetail.endTime)}</span>
                      </div>
                      <div className="flex justify-between">
                        <span className="text-gray-600">课时：</span>
                        <span className="text-gray-900">{courseDetail.courseHours}小时</span>
                      </div>
                      <div className="flex justify-between">
                        <span className="text-gray-600">考试时间：</span>
                        <span className="text-gray-900">{formatDate(courseDetail.testTime)}</span>
                      </div>
                    </div>
                  </div>
                </div>
              )}
              
              {/* 确认提示 */}
              <div className="bg-blue-50 border border-blue-200 rounded-lg p-4 mb-6">
                <p className="text-blue-800 text-sm">
                  <i className="fas fa-info-circle mr-2"></i>
                  请仔细核对以上信息，确保无误后再进行报名。
                </p>
              </div>
              
              {/* 操作按钮 */}
              <div className="flex space-x-3">
                <button
                  onClick={() => setIsEnrollModalVisible(false)}
                  className="flex-1 py-3 border border-gray-300 text-gray-600 rounded-lg hover:bg-gray-50 transition-colors"
                >
                  取消
                </button>
                <button
                  onClick={handleConfirmEnroll}
                  disabled={!userInfo || enrolling || enrollSuccess}
                  className={`flex-1 py-3 rounded-lg text-white transition-colors ${
                    (!userInfo || enrolling || enrollSuccess) 
                      ? 'bg-gray-400 cursor-not-allowed' 
                      : 'bg-blue-600 hover:bg-blue-700'
                  }`}
                >
                  {enrolling ? '提交中...' : enrollSuccess ? '报名成功' : '确认报名'}
                </button>
              </div>
            </div>
          </div>
        </div>
      )}
    </Layout>
  );
};

export default CourseDetailPage;

